/*
 * Copyright (c) 2016. danlu.com Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.category.CategoryActivity;
import cn.com.dhc.danlu.activity.home.HomeActivity;
import cn.com.dhc.danlu.activity.home.wrap.CategoryEvent;
import cn.com.dhc.danlu.activity.myself.MyselfActivity;
import cn.com.dhc.danlu.business.shopcar.activity.ShopCarActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.model.bus.BaseEvent;
import cn.com.dhc.danlu.util.ACache;
import cn.com.dhc.danlu.util.ActivePhoneProcess;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ContextUtils;
import cn.com.dhc.danlu.util.PushEngine;
import cn.com.dhc.danlu.util.TipCountUtil;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.BadgeView;
import cn.com.dhc.danlu.widget.adapter.GeneralGoodsAdapter;
import cn.com.hd.mall.web.webservices.entity.freedom.request.base.BaseRequest;
import cn.com.hd.mall.web.webservices.entity.response.login.LoginResponse;
import cn.com.hd.mall.web.webservices.entity.response.shoppingcart.ShoppingCartSizeResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @author: MuWei
 * @version: 1.0.0
 * @since: 2015/02/03 00:00
 * @email: null
 * @desc: 主菜单画面
 */
public class MainMenuActivity extends ActivityGroup implements CheckVersionDelegate.CheckVersionListener {
    /**
     * Tab id 首页
     */
    public static final String ID_HOME_PAGE = "homepage";
    /**
     * Tab id 分类
     */
    public static final String ID_CATEGORY = "category";
    /**
     * Tab id 购物车
     */
    public static final String ID_SHOP_CART = "shopCart";
    /**
     * Tab id 我的
     */
    public static final String ID_MYSELF = "myself";
    /**
     * 角标
     */
    @SuppressLint("StaticFieldLeak")
    public static BadgeView shopCart;
    /**
     * 退出时间
     */
    private long exitTime = 0;
    /**
     * Activity容器
     */
    private LinearLayout llytContainer;
    /**
     * 首页tab
     */
    private LinearLayout llytHomePage;
    /**
     * 分类tab
     */
    private LinearLayout llytCategory;
    /**
     * 购物车tab
     */
    private LinearLayout llytShopCart;
    /**
     * 我的tab
     */
    private LinearLayout llytMyself;
    /**
     * 首页图标
     */
    private ImageView imgHomePage;
    /**
     * 分类图标
     */
    private ImageView imgCategory;
    /**
     * 购物车图标
     */
    private ImageView imgShopCart;
    /**
     * 我的图标
     */
    private ImageView imgMyself;
    /**
     * 首页文字
     */
    private TextView txtHomepage;
    /**
     * 分类文字
     */
    private TextView txtCategory;
    /**
     * 购物车文字
     */
    private TextView txtShopCart;
    /**
     * 我的文字
     */
    private TextView txtMyself;
    /**
     * 购物车角标llyt
     */
    private LinearLayout llytImgShopCart;

    private String mCurrentTabStr;
    /**
     * 切换Tab监听。
     */
    private View.OnClickListener onTabClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.llytHomePage:
                    // 显示首页Tab
                    showTab(ID_HOME_PAGE, HomeActivity.class, v.getId());
                    break;

                case R.id.llytCategory:
                    // 显示分类Tab
                    showTab(ID_CATEGORY, CategoryActivity.class, v.getId());
                    break;

                case R.id.llytShopCart:
                    // 显示购物车
                    showTab(ID_SHOP_CART, ShopCarActivity.class, v.getId());
//                    showTab(ID_SHOP_CART, ShopCartActivity.class, v.getId());
                    break;

                case R.id.llytMyself:
                    // 显示我的Tab
                    showTab(ID_MYSELF, MyselfActivity.class, v.getId());
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * 定义广播接收器
     */
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_COUNT_ACTION)) {
                sendGetShoppingcartCountRequest();
            }
            if (action.equals(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_ACTION)) {
                showTab(ID_CATEGORY, CategoryActivity.class, R.id.llytCategory);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main_menu);

        initViews();

        // 版本检查代理类
        CheckVersionDelegate checkVersionDelegate = new CheckVersionDelegate(this, this);
        checkVersionDelegate.setCheckActiveListener(new CheckVersionDelegate.OnWhenActiveListener() {
            @Override
            public void checkActive() {
                LoginResponse loginUser = agent.getLoginUser();
                if (null != loginUser && !TextUtils.isEmpty(loginUser.getTelStatus()) && loginUser.getTelStatus().equals("1")) {
                    ActivePhoneProcess process = new ActivePhoneProcess();
                    process.setSwitchFragmentStatus(true);
                    process.showActiveDialog(MainMenuActivity.this, false);
                }
            }
        });
        // 获取版本
        checkVersionDelegate.getVersion();
        // 画面初始化
        init();
        EventBus.getDefault().register(this);
        PushEngine.newInstance().getRegisterId();
    }

    private void initViews() {
        llytContainer = (LinearLayout) findViewById(R.id.llytContainer);
        llytHomePage = (LinearLayout) findViewById(R.id.llytHomePage);
        llytCategory = (LinearLayout) findViewById(R.id.llytCategory);
        llytShopCart = (LinearLayout) findViewById(R.id.llytShopCart);
        llytMyself = (LinearLayout) findViewById(R.id.llytMyself);
        imgHomePage = (ImageView) findViewById(R.id.imgHomePage);
        imgCategory = (ImageView) findViewById(R.id.imgCategory);
        imgShopCart = (ImageView) findViewById(R.id.imgShopCart);
        imgMyself = (ImageView) findViewById(R.id.imgMyself);
        txtHomepage = (TextView) findViewById(R.id.txtHomepage);
        txtCategory = (TextView) findViewById(R.id.txtCategory);
        txtShopCart = (TextView) findViewById(R.id.txtShopCart);
        txtMyself = (TextView) findViewById(R.id.txtMyself);
        llytImgShopCart = (LinearLayout) findViewById(R.id.llytImgShopCart);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        releaseRef();
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 获取购物车商品数量
        sendGetShoppingcartCountRequest();
    }

    /**
     * 后期优化代码的时候可以将 这块逻辑抽取出去
     */
    @Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
    public void onSelectType(CategoryEvent event) {
        Intent intent = new Intent(MainMenuActivity.this, CategoryActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)
                .putExtra("code", event.categroyCode).putExtra("des", event.description)
                .putExtra("brandId", event.brandId);
        switchSelectTypeTab(intent);
        mCurrentTabStr = ID_CATEGORY;
    }

    @Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
    public void onSearch(Intent event) {
        Intent intent = new Intent(MainMenuActivity.this, CategoryActivity.class)
                .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)
                .putExtra(CommonConst.IntentKey.SEARCH_RANGE_KEY, event.getBooleanExtra(CommonConst.IntentKey.SEARCH_RANGE_KEY, false))
                .putExtra(CommonConst.IntentKey.KEY_WORD, event.getStringExtra(CommonConst.IntentKey.KEY_WORD));
        switchSelectTypeTab(intent);
        mCurrentTabStr = ID_CATEGORY;

    }

    @Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
    public void refreshShopCartNum(BaseEvent event) {
        if (event.getEventFrom().equals(GeneralGoodsAdapter.REFRESH_BADGE_SHOPCARD)) {
            // 获取购物车商品数量
            sendGetShoppingcartCountRequest();
        }
    }

    /**
     * 获取购物车商品数量
     */
    private void sendGetShoppingcartCountRequest() {
        BaseRequest request = new BaseRequest();
        request.setToken(agent.getToken());
        agent.getApi().getShoppingCartCount(request)
                .compose(OperatorUtils.<ShoppingCartSizeResponse> defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<ShoppingCartSizeResponse>() {
                    @Override
                    protected void onSuccess(ShoppingCartSizeResponse model) {
                        updateBdvViewShoppingCarCount(model.getShoppingCartSize());
                    }
                });
    }

    public void releaseRef() {
        EventBus.getDefault().unregister(this);
        unregisterReceiver(mBroadcastReceiver);
    }

    /**
     * 画面初始化
     */
    private void init() {
        // 显示首页Tab
        showTab(ID_HOME_PAGE, HomeActivity.class, R.id.llytHomePage);
        // 设置监听
        setListener();
        // 注册获取购物车数量广播
        registerBoradcastReceiver();
    }

    /**
     * Tab切换
     *
     * @param id
     *         TabId
     * @param activityClassName
     *         Tab对应的Activity的类名
     */
    public void showTab(String id, Class<?> activityClassName, int viewId) {
        if (!TextUtils.isEmpty(mCurrentTabStr) && mCurrentTabStr.equals(id)) {
            return;
        }
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        llytContainer.removeAllViews();
        View decorView = getLocalActivityManager().startActivity(id, new Intent(MainMenuActivity.this, activityClassName).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP)).getDecorView();
        CommonUtils.removeViewParent(decorView);
        llytContainer.addView(decorView, params);
        // 设置Tab选中效果
        selectTabLayout(viewId);
        // 触发当前选中activity start 事件
        Activity currentActivity = getLocalActivityManager().getCurrentActivity();
        if (currentActivity != null && currentActivity instanceof IActivityEventListener) {
            IActivityEventListener iActivityEventListener = (IActivityEventListener) currentActivity;
            iActivityEventListener.onActivityStart();
        }
        this.mCurrentTabStr = id;
    }


    /**
     * 设置监听
     */
    private void setListener() {
        // Tab添加点击监听
        llytHomePage.setOnClickListener(onTabClickListener);
        llytCategory.setOnClickListener(onTabClickListener);
        llytShopCart.setOnClickListener(onTabClickListener);
        llytMyself.setOnClickListener(onTabClickListener);
    }

    /**
     * 注册获取发送购物车数量的广播通知
     */
    public void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_COUNT_ACTION);
        myIntentFilter.addAction(CommonConst.BroadcastAction.BROADCAST_GET_SHOPPINGCART_ACTION);
        // 注册广播
        registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    /**
     * Tab选中效果
     *
     * @param viewId
     *         选中Tab的Id
     */
    private void selectTabLayout(int viewId) {
        // 首页Tab
        if (R.id.llytHomePage == viewId) {
            imgHomePage.setImageResource(R.drawable.ic_home_press);
            txtHomepage.setTextColor(getResources().getColor(R.color.color_af272a));
        } else {
            imgHomePage.setImageResource(R.drawable.ic_home_unpress);
            txtHomepage.setTextColor(Color.GRAY);
        }
        // 分类Tab
        if (R.id.llytCategory == viewId) {
            imgCategory.setImageResource(R.drawable.category_tab_main_red);
            txtCategory.setTextColor(getResources().getColor(R.color.color_af272a));
        } else {
            imgCategory.setImageResource(R.drawable.category_tab_main_white);
            txtCategory.setTextColor(Color.GRAY);
        }

        // 购物车Tab
        if (R.id.llytShopCart == viewId) {
            imgShopCart.setImageResource(R.drawable.category_tab_shop_red);
            txtShopCart.setTextColor(getResources().getColor(R.color.color_af272a));
        } else {
            imgShopCart.setImageResource(R.drawable.category_tab_shop_white);
            txtShopCart.setTextColor(Color.GRAY);
        }

        // 我的Tab
        if (R.id.llytMyself == viewId) {
            imgMyself.setImageResource(R.drawable.category_tab_my_red);
            txtMyself.setTextColor(getResources().getColor(R.color.color_af272a));
        } else {
            imgMyself.setImageResource(R.drawable.category_tab_my_white);
            txtMyself.setTextColor(Color.GRAY);
        }
    }


    private void switchSelectTypeTab(Intent intent) {
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        llytContainer.removeAllViews();
        llytContainer.addView(getLocalActivityManager().startActivity(ID_CATEGORY, intent).getDecorView(), params);
        // 设置Tab选中效果
        selectTabLayout(R.id.llytCategory);
        // 触发当前选中activity start 事件
        Activity currentActivity = getLocalActivityManager().getCurrentActivity();
        if (currentActivity != null && currentActivity instanceof IActivityEventListener) {
            IActivityEventListener iActivityEventListener = (IActivityEventListener) currentActivity;
            iActivityEventListener.onActivityStart();
        }
    }

    /**
     * 更新购物车角标数量
     */
    private void updateBdvViewShoppingCarCount(int count) {
        // 设置角标
        if (shopCart == null) {
            shopCart = new BadgeView(this, llytImgShopCart);
        }
        shopCart.setBadgeMargin(0, 0);
        shopCart.setText(TipCountUtil.cover(count, TipCountUtil.SMALL_FLAG));
        shopCart.setTextSize(10);
        if (count < 1) {
            shopCart.hide();
        } else {
            shopCart.show();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getBooleanExtra("switchCategory", false)) {
            // 暂时不考虑角色
            // 设置Tab选中效果
            // 显示分类Tab
            showTab(ID_CATEGORY, CategoryActivity.class, R.id.llytCategory);
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 重写返回键
        if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (getLocalActivityManager().getCurrentId().equals(ID_SHOP_CART) && ((ShopCarActivity) getCurrentActivity()).isShowPopupWindow()) {
                return getLocalActivityManager().getCurrentActivity().onKeyDown(event.getKeyCode(), event);
            } else {
                // 按两次返回键才退出程序
                exit();
            }
            return false;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 退出丹露
     */
    private void exit() {
        // 按两次返回键才退出程序
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            // 第一次按返回键，弹出Toast提醒
            ToastUtil.getInstance().show(R.string.exit_app);
            exitTime = System.currentTimeMillis();
        } else {
            // 用来保存统计数据
            MobclickAgent.onKillProcess(getApplicationContext());
            // 清除缓存
            CommonUtils.clearAllCgrPrtBrd(getApplicationContext());
            ACache.get(getApplicationContext()).remove("count");
            ACache.get(getApplicationContext()).remove("isClick");
            releaseRef();
            // 第二次按返回键，退出程序
            ContextUtils.destroy(MainMenuActivity.this);
            finish();
        }
    }

    @Override
    public void finishActivity() {
        this.finish();
    }
}